<!DOCTYPE html>
<html>
<head>
    <title>任务管理</title>
    {% include 'system/common/header.html' %}
</head>
<body class="ppress-container">

<div class="layui-card">
    <div class="layui-card-body">
        <table id="task-table" lay-filter="task-table"></table>
    </div>
</div>
</body>

<script type="text/html" id="task-toolbar">
    {% if authorize("system:task:add") %}
        <button class="layui-btn layui-btn-primary layui-btn-sm" lay-event="add">
            <i class="ppress-icon ppress-icon-add"></i>
            {{ _('ADD') }}
        </button>
        <a href="{{ url_for('i18n.switch_language', lang='zh') }}"
           class="layui-btn layui-btn-primary layui-btn-sm language-btn {% if session.get('lang', 'zh') == 'zh' %}active{% endif %}">
            中文
        </a>
        <a href="{{ url_for('i18n.switch_language', lang='en') }}"
           class="layui-btn layui-btn-primary layui-btn-sm language-btn {% if session.get('lang') == 'en' %}active{% endif %}">
            English
        </a>
        <a href="{{ url_for('i18n.switch_language', lang='ja') }}"
           class="layui-btn layui-btn-primary layui-btn-sm language-btn {% if session.get('lang') == 'ja' %}active{% endif %}">
            日本語
        </a>
        <a href="{{ url_for('i18n.switch_language', lang='ko') }}"
           class="layui-btn layui-btn-primary layui-btn-sm language-btn {% if session.get('lang') == 'ko' %}active{% endif %}">
            한국어
        </a>
    {% endif %}
</script>

<script type="text/html" id="task-bar">
    {% if authorize("system:task:edit") %}
        <button class="layui-btn layui-btn-xs" lay-event="edit">
            <i class="ppress-icon ppress-icon-edit"> {{ _('UPDATE') }}</i>
        </button>
    {% endif %}
    {% if authorize("system:task:edit") %}
        <button class="layui-btn layui-btn-normal layui-btn-xs" lay-event="run">
            <i class="layui-icon layui-icon-play"></i>
        </button>
    {% endif %}
    {% if authorize("system:task:remove") %}
        <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="remove">
            <i class="ppress-icon ppress-icon-ashbin"> {{ _('DELETE') }}</i>
        </button>
    {% endif %}
</script>

<script type="text/html" id="task-status">
    <input type="checkbox" name="enable" lay-skin="switch" lay-text="正在运行|已经暂停"
           lay-filter="task-enable" id="task-switch">
</script>

<script type="text/html" id="task-createTime">
    <span id="create-time"></span>
</script>

<script type="text/html" id="task-nextRun">
    <span id="next-run"></span>
</script>

{% include 'system/common/footer.html' %}
<script>
  layui.use(['table', 'form', 'jquery', 'popup', 'common'], function () {
    let table = layui.table
    let form = layui.form
    let $ = layui.jquery
    let popup = layui.popup

    let MODULE_PATH = '/admin/sys/task/'

    let cols = [
      [
        { type: 'checkbox' },
        { title: 'ID', field: 'id', align: 'center', width: 120 },
        { title: '{{ _('FUNCTION') }}', field: 'func', align: 'center', width: 120 },
        { title: '{{ _('NAME') }}', field: 'name', align: 'center', width: 150 },
        { title: '{{ _('CREATE_TIME') }}', field: 'start_date', align: 'center', width: 160, templet: '#task-createTime'},
        { title: '{{ _('IS_IT_RUNNING') }}', field: 'next_run_time', align: 'center', width: 160, templet: '#task-nextRun'},
        { title: '{{ _('NEXT_RUN') }}', field: 'enabled', align: 'center', width: 120, templet: '#task-status' },
        { title: '{{ _('TYPE') }}', field: 'trigger', align: 'center', width: 100 },
        { title: '{{ _('OPERATION') }}', toolbar: '#task-bar', align: 'center' }
      ]
    ]

    table.render({
      elem: '#task-table',
      url: MODULE_PATH + 'data',
      page: true,
      cols: cols,
      skin: 'line',
      toolbar: '#task-toolbar',
      defaultToolbar: [{
        layEvent: 'refresh',
        icon: 'layui-icon-refresh',
      }, 'filter', 'print', 'exports'],
      done: function(res, curr, count) {
        // 渲染完成后处理模板
        $('.layui-table-body tbody tr').each(function() {
          let $tr = $(this);
          let data = table.cache['task-table'][$tr.data('index')];
          if (data) {
            // 处理创建时间
            let $createTime = $tr.find('#create-time');
            if (data.created_at) {
              $createTime.text(data.created_at);
            }
            
            // 处理下次运行时间
            let $nextRun = $tr.find('#next-run');
            if (data.next_run_time) {
              $nextRun.text(data.next_run_time);
            } else {
              $nextRun.text('未设置');
            }
            
            // 处理状态开关
            let $switch = $tr.find('#task-switch');
            $switch.attr('value', data.id);
            if (data.enabled) {
              $switch.prop('checked', true);
            } else {
              $switch.prop('checked', false);
            }
          }
        });
        form.render('checkbox');
      }
    })

    table.on('tool(task-table)', function (obj) {
      if (obj.event === 'remove') {
        window.remove(obj)
      } else if (obj.event === 'edit') {
        window.edit(obj)
      } else if (obj.event === 'run') {
        window.runNow(obj)
      }
    })

    table.on('toolbar(task-table)', function (obj) {
      if (obj.event === 'add') {
        window.add()
      } else if (obj.event === 'refresh') {
        window.refresh()
      } else if (obj.event === 'batchRemove') {
        window.batchRemove(obj)
      }
    })

    form.on('switch(task-enable)', function (obj) {
      let operate
      if (obj.elem.checked) {
        operate = 'enable'
      } else {
        operate = 'disable'
      }
      let loading = layer.load()
      $.ajax({
        url: '/admin/sys/task/' + operate,
        data: JSON.stringify({ id: this.value }),
        dataType: 'json',
        contentType: 'application/json',
        type: 'put',
        success: function (result) {
          layer.close(loading)
          if (result.success) {
            layer.msg(result.msg, { icon: 1, time: 1000 })
          } else {
            layer.msg(result.msg, { icon: 2, time: 1000 })
            // 如果操作失败，恢复开关状态
            obj.elem.checked = !obj.elem.checked;
            form.render('checkbox');
          }
        },
        error: function() {
          layer.close(loading)
          layer.msg('操作失败', { icon: 2, time: 1000 })
          // 恢复开关状态
          obj.elem.checked = !obj.elem.checked;
          form.render('checkbox');
        }
      })
    })

    window.add = function () {
      layer.open({
        type: 2,
        title: '新增任务',
        shade: 0.1,
        area: ['600px', '500px'],
        content: MODULE_PATH + 'add'
      })
    }

    window.edit = function (obj) {
      layer.open({
        type: 2,
        title: '编辑任务',
        shade: 0.1,
        area: ['600px', '500px'],
        content: MODULE_PATH + 'edit/' + obj.data['id']
      })
    }

    window.runNow = function (obj) {
      layer.confirm('确定要立即运行该任务吗？', { icon: 3, title: '提示' }, function (index) {
        layer.close(index)
        let loading = layer.load()
        $.ajax({
          url: MODULE_PATH + 'run/' + obj.data['id'],
          dataType: 'json',
          type: 'post',
          success: function (result) {
            layer.close(loading)
            if (result.success) {
              layer.msg(result.msg, { icon: 1, time: 1000 })
            } else {
              layer.msg(result.msg, { icon: 2, time: 1000 })
            }
          },
          error: function() {
            layer.close(loading)
            layer.msg('运行失败', { icon: 2, time: 1000 })
          }
        })
      })
    }

    window.remove = function (obj) {
      layer.confirm('确定要删除该任务吗？', { icon: 3, title: '提示' }, function (index) {
        layer.close(index)
        let loading = layer.load()
        $.ajax({
          url: MODULE_PATH + 'remove/' + obj.data['id'],
          dataType: 'json',
          type: 'delete',
          success: function (result) {
            layer.close(loading)
            if (result.success) {
              layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                obj.del()
              })
            } else {
              layer.msg(result.msg, { icon: 2, time: 1000 })
            }
          },
          error: function() {
            layer.close(loading)
            layer.msg('删除失败', { icon: 2, time: 1000 })
          }
        })
      })
    }

    window.refresh = function () {
      table.reload('task-table')
    }
  })
</script>
</html>